package logs


import (
	"sync"
	"time"
	"os"
	//"strings"
	//"path/filepath"
	"encoding/json"
	"errors"
)

/**
@attr FileName 文件名
@attr sync.Mutex 锁

 */
type fileWriter struct  {
	FileName string `json:"filename"`
	Level int `json:"level"`
	fileWriter *os.File
	sync.Mutex

}


func NewFileWrite() Output {
	w := &fileWriter{
		FileName: "",
		Level:DebugLevel,
	}
	return w
}

func (w *fileWriter) Set(config []byte) error {
	err := json.Unmarshal(config, w)
	if err != nil {
		return err
	}
	if len(w.FileName) == 0 {
		return errors.New("config must have filename")
	}

	err = w.start()
	return err
}


func (w *fileWriter) Write(when time.Time, msg string, level int) error  {
	if level < w.Level {
		return nil
	}
	head := formatTimeHeader(when)
	w.Lock()
	_,err := w.fileWriter.Write(append(append(head, msg ...), '\n'))
	w.Unlock()
	return err
}


func (w *fileWriter) Close()  {
	w.fileWriter.Close()
}

func (w *fileWriter) Flush()  {
	w.fileWriter.Sync()
}



func (w *fileWriter) start() error {
	file,err := w.createLogFile()
	if err != nil {
		return err
	}
	if w.fileWriter != nil { //关闭已经打开的文件
		w.fileWriter.Close()
	}
	w.fileWriter = file
	return nil

}

func (w *fileWriter) createLogFile() (*os.File, error) {
	//open the log file
	fd,err := os.OpenFile(w.FileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
	return fd,err
}

func init()  {
	Register("file", NewFileWrite)
}